package in.srain.cube.views.list;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.request.JsonData;
import in.srain.cube.request.RequestData;

public class ListPageInfo<ListItemDataType> {

    public final List<ListItemDataType> dataList = new ArrayList<>();
    private final int mNumPerPage;
    private boolean mHasNext;
    private int mStart = 0;
    private String mLastId = null;

    public ListPageInfo(int numPerPage) {
        this.mNumPerPage = numPerPage;
    }

    public void appendQueryDataTo(RequestData requestData) {
        requestData.addQueryData("start", mStart);
        requestData.addQueryData("num", mNumPerPage);
        requestData.addQueryData("lastObjectId", mLastId);
    }

    public void appendPostDataTo(RequestData requestData) {
        requestData.addPostData("start", mStart);
        requestData.addPostData("num", mNumPerPage);
        requestData.addPostData("lastObjectId", mLastId);
    }

    public void updateResult(JsonData rawData, List<? extends ListItemDataType> list) {
        mHasNext = rawData.optBoolean("hasNext");
        if (rawData.has("lastObjectId")) {
            mLastId = rawData.optString("lastObjectId");
        }
        if (list == null) {
            return;
        }
        if (mStart == 0) {
            dataList.clear();
        }
        final int count = rawData.optJson("list").length();
        mStart += mNumPerPage;
        dataList.addAll(list);
    }

    /**
     * start from 0
     *
     * @return
     */
    public int getPage() {
        return mStart / mNumPerPage;
    }

    public void reset() {
        mHasNext = false;
        mStart = 0;
        mLastId = null;
    }

    public void resetAndClearList() {
        reset();
        dataList.clear();
    }

    public ListItemDataType getItem(int position) {
        if (null == dataList || position < 0 || position > dataList.size()) {
            return null;
        }
        return dataList.get(position);
    }

    public boolean isEmpty() {
        return dataList.size() == 0;
    }

    public List<ListItemDataType> getDataList() {
        return dataList;
    }

    public boolean hasMore() {
        return mHasNext;
    }

    public boolean isFirstPage() {
        return 0 == mStart;
    }

    public int getNumPerPage() {
        return mNumPerPage;
    }
}